<template>
	<view >
		<cl-navbar :title="$t('chat.business_share.title')" leftIconSize="40rpx" placeholder autoBack>
		</cl-navbar>
		<view class="searchview">
			<u-search :showAction="true" height="64rpx" :clearabled="false" searchIconColor="#61626E"
				searchIconSize="40rpx" :actionText="$t('commonality.search')" bgColor="#1e1f30" placeholder=""
				:actionStyle="{ color: '#61626E', fontSize: '26rpx' }"></u-search>
		</view>

		<view class="listview">
			<view class="mycollapse">
				<view class="mycollapse__view" @click="collapses.chatRecently = !collapses.chatRecently">
					<text class="mycollapse__view__title">最近聊天</text>
					<u-icon :name="collapses.chatRecently?'arrow-down':'arrow-right'" color="#ffffff" size="15px"></u-icon>
				</view>
				<view v-show="collapses.chatRecently">
					<u-list height="100%">
						<!-- 置顶 -->
						<view style="background-color: #1e1f30;border-radius: 40rpx;">
							<template v-for="(item, index) in filtrationList">
								<u-list-item v-if="item.is_top" :key="index">
									<view class="listitemtop" @click="itemclick(item)">
										<view class="listitem__left">
											<cl-avatar :src="item.chat_face" size="100rpx"></cl-avatar>
										</view>
										<view class="listitem__right">
											<view class="listitem__right__top">
												<text class="listitem__right__top__nickname">{{item.chat_name}}</text>
											</view>
										</view>
									</view>
								</u-list-item>
							</template>
						</view>
						<!-- 非置顶 -->
						<template v-for="(item, index) in filtrationList">
							<u-list-item v-if="!item.is_top" :key="index">
								<view class="listitem"  @click="itemclick(item)">
									<view class="listitem__left">
										<cl-avatar :src="item.chat_face" size="100rpx"></cl-avatar>
									</view>
									<view class="listitem__right">
										<view class="listitem__right__top">
											<text class="listitem__right__top__nickname">{{item.chat_name}}</text>
										</view>
									</view>
								</view>
							</u-list-item>
						</template>
					</u-list>
				</view>
			</view>
			<!-- //分组 -->
			<view class="mycollapse">
				<view class="mycollapse__view" @click="collapses.friendGroup = !collapses.friendGroup">
					<text class="mycollapse__view__title">最近聊天</text>
					<u-icon :name="collapses.friendGroup?'arrow-down':'arrow-right'" color="#ffffff" size="15px"></u-icon>
				</view>
				<view v-show="collapses.friendGroup">
					<u-collapse :border="false" ref="collapses" @change="openFriendGroup">
						<u-collapse-item :title="item.group_name" :clickable="false" :isLink="false" v-for="(item,index) in friendGroupList" :key="index">
							<text slot="value" class="groupvalue">
								{{item.data.length}}
							</text>
							<view class="listitemview">
								<view class="listitem" v-for="(cell, idx) in item.data" :key="'item'+idx" @click="goFriend(cell)">
									<view class="listitem__left">
										<cl-avatar :src="cell.avatar_url" size="100rpx"></cl-avatar>
									</view>
									<view class="listitem__right">
										<view class="listitem__right__top">
											<text class="listitem__right__top__nickname">{{cell.friend_remark || cell.nick_name}}</text>
										</view>
										<view class="listitem__right__content">
											<text v-if="friendOnline[cell.friend_idx]" style="color: #6aaf76;font-size: 24rpx;">[{{$t("common.friend.online")}}]</text>
											<text v-else style="color: #595A66;font-size: 24rpx;">[{{$t("common.friend.offline")}}]</text>
										</view>
									</view>
								</view>
							</view>
						</u-collapse-item>
					</u-collapse>
				</view>
			</view>
			
			<!-- //群组 -->
			<view class="mycollapse">
				<view class="mycollapse__view" @click="collapses.group = !collapses.group">
					<text class="mycollapse__view__title">最近聊天</text>
					<u-icon :name="collapses.group?'arrow-down':'arrow-right'" color="#ffffff" size="15px"></u-icon>
				</view>
				<view v-show="collapses.group">
					<z-paging ref="paging" default-page-size="2" :show-default-loading-more-text="false" :fixed="false" :use-page-scroll="true" v-model="indexList" @query="queryList" safe-area-inset-bottom use-safe-area-placeholder :show-loading-more-no-more-view="false" :refresher-enabled = "false">
						<view :key="index" v-for="(item, index) in searchlist"> 
							<view class="listitem"  @click="godetails(item.group_info)">
								<view class="listitem__left">
									<cl-avatar :src="item.group_info.avatar_url" size="100rpx"></cl-avatar>
								</view>
								<view class="listitem__right">
									<view class="listitem__right__top">
										<text class="listitem__right__top__nickname">{{item.group_info.group_name}}</text>
									</view>
								</view>
							</view>
						</view>
					</z-paging>
				</view>
			</view>
			
			
			
			<uni-collapse ref="collapse" v-model="collapseValue">
				<uni-collapse-item :title="$t('chat.business_share.chatRecently')" :border="false"  title-border = "none">
					<u-list height="100%">
						<!-- 置顶 -->
						<view style="background-color: #1e1f30;border-radius: 40rpx;">
							<template v-for="(item, index) in filtrationList">
								<u-list-item v-if="item.is_top" :key="index">
									<view class="listitemtop" @click="itemclick(item)">
										<view class="listitem__left">
											<cl-avatar :src="item.chat_face" size="100rpx"></cl-avatar>
										</view>
										<view class="listitem__right">
											<view class="listitem__right__top">
												<text class="listitem__right__top__nickname">{{item.chat_name}}</text>
											</view>
										</view>
									</view>
								</u-list-item>
							</template>
						</view>
						<!-- 非置顶 -->
						<template v-for="(item, index) in filtrationList">
							<u-list-item v-if="!item.is_top" :key="index">
								<view class="listitem"  @click="itemclick(item)">
									<view class="listitem__left">
										<cl-avatar :src="item.chat_face" size="100rpx"></cl-avatar>
									</view>
									<view class="listitem__right">
										<view class="listitem__right__top">
											<text class="listitem__right__top__nickname">{{item.chat_name}}</text>
										</view>
									</view>
								</view>
							</u-list-item>
						</template>
					</u-list>
				</uni-collapse-item>
				<uni-collapse-item :title="$t('group.group_list.title')" :border="false" title-border = "none">
					<u-collapse :border="false" ref="collapses" @change="openFriendGroup">
						<u-collapse-item :title="item.group_name" :clickable="false" :isLink="false" v-for="(item,index) in friendGroupList" :key="index">
							<text slot="value" class="groupvalue">
								{{item.data.length}}
							</text>
							<view class="listitemview">
								<view class="listitem" v-for="(cell, idx) in item.data" :key="'item'+idx" @click="goFriend(cell)">
									<view class="listitem__left">
										<cl-avatar :src="cell.avatar_url" size="100rpx"></cl-avatar>
									</view>
									<view class="listitem__right">
										<view class="listitem__right__top">
											<text class="listitem__right__top__nickname">{{cell.friend_remark || cell.nick_name}}</text>
										</view>
										<view class="listitem__right__content">
											<text v-if="friendOnline[cell.friend_idx]" style="color: #6aaf76;font-size: 24rpx;">[{{$t("common.friend.online")}}]</text>
											<text v-else style="color: #595A66;font-size: 24rpx;">[{{$t("common.friend.offline")}}]</text>
										</view>
									</view>
								</view>
							</view>
						</u-collapse-item>
					</u-collapse>
				</uni-collapse-item>
				<uni-collapse-item :title="$t('group.group_list.title')" :border="false" title-border = "none">
					<z-paging ref="paging" default-page-size="2" :show-default-loading-more-text="false" :fixed="false" :use-page-scroll="true" v-model="indexList" @query="queryList" safe-area-inset-bottom use-safe-area-placeholder :show-loading-more-no-more-view="false" :refresher-enabled = "false">
						<view :key="index" v-for="(item, index) in searchlist"> 
							<view class="listitem"  @click="godetails(item.group_info)">
								<view class="listitem__left">
									<cl-avatar :src="item.group_info.avatar_url" size="100rpx"></cl-avatar>
								</view>
								<view class="listitem__right">
									<view class="listitem__right__top">
										<text class="listitem__right__top__nickname">{{item.group_info.group_name}}</text>
									</view>
								</view>
							</view>
						</view>
					</z-paging>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		<view>
			<cl-model ref="clShare">
				<view class="shareView">
					<text class="shareView__title">{{$t("chat.business_share.Sendto")}}</text>
					<view class="shareView__top">
						<cl-avatar
							:src="chatInfo.chat_face"
							size="60rpx"></cl-avatar>
						<text class="shareView__top__name">{{chatInfo.nick_name}}</text>
					</view>
					
					<view class="shareView__content" v-if="chatdata.length == 1">
						<view class="content" v-if="chatdata[0].msg_type == 'text'">
							<rich-text :nodes="messageText(chatdata[0].content_text[0].text.content)" :selectable="false" style="white-space: pre-wrap;"></rich-text>
						</view>
						<view class="content" v-if="chatdata[0].msg_type == 'audio'">
							<text>{{[this.$t("chat.msg.type.audio")]}}</text>
						</view>
						
						<view class="content" v-else-if="chatdata[0].msg_type == 'mixed'">
							<cl-chat-img-video :imgList="mediaAttachments(chatdata[0])" v-if="mediaAttachments(chatdata[0]).length!=0" width="400"></cl-chat-img-video>
							<view v-for="(attachment, arrindex) in chatdata[0].content_text" :key="arrindex">
								<view v-if="attachment.text" style="margin: 15rpx 10rpx;">
									<rich-text :nodes="messageText(attachment.text.content)" :selectable="false" style="white-space: pre-wrap;"></rich-text>
								</view>
							</view>
						</view>
						<view class="content" v-else-if="chatdata[0].msg_type == 'image'">
							<cl-chat-img-video :imgList="chatdata[0].content_text" width="400"></cl-chat-img-video>
						</view>
						<view class="content" v-else-if="chatdata[0].msg_type == 'video'">
							<cl-chat-img-video :imgList="chatdata[0].content_text" width="400"></cl-chat-img-video>
						</view>
						<view class="content" v-else-if="chatdata[0].msg_type == 'b_c'">
							<text class="u-line-1">{{chatdata[0].content_text[0].b_c.type == 'private'?`[${$t("chat.msg.type.personalCard")}]`:chatdata[0].content_text[0].b_c.type == 'group'?`[${$t("chat.msg.type.groupCard")}]`:`[${$t("chat.msg.type.otherCard")}]`}}{{chatdata.content_text[0].b_c.nick_name}}</text>
						</view>
					</view>
					<view class="shareView__content" v-else>
						<view class="content">
							<text class="u-line-1">{{$tc("chat.business_share.multiMessage",chatdata.length)}}</text>
						</view>
					</view>
				</view>
			</cl-model>
		</view>
		
	</view>
</template>

<script>
	import {
		v4 as uuidv4
	} from 'uuid';
	import messageApi from '@/services/api/msg.js'
	import friendGroupApi from "@/services/api/friendsGroup.js"
	import {
		replaceEmojis
	} from '@/components/cl-chat-input/o-emoji/emoji.js';
	import {
		mapState
	} from 'vuex'
	import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
	export default {
		mixins: [ZPMixin],
		data() {
			return {
				collapses:{
					chatRecently:true,
					friendGroup:false,
					group:false
				},
				
				
				grouplist:[],//分组列表
				
				type:'',
				chatdata:[],
				chatInfo:{},
				
				indexList: [],//群列表
				searchval:''//搜索文字
			};
		},
		computed: {
			...mapState({
				sessionList: state => state.session.sessionList,
				friendList: state => state.friends.friendList,
				friendOnline: state => state.friends.friendOnline,
			}),
			friendGroupList(){
				//这里是现在离线排序，要求的时候再打开
				let friendData = JSON.parse(JSON.stringify(this.friendList))
				friendData.sort((friend1, friend2) => {
					  const isFriend1Online = this.friendOnline[friend1.friend_idx] || false; // 判断friend1是否在线
					  const isFriend2Online = this.friendOnline[friend2.friend_idx] || false; // 判断friend2是否在线
					  
					  // 如果friend1在线而friend2不在线，将friend1排在前面
					  if (isFriend1Online && !isFriend2Online) {
						return -1;
					  }
					  // 如果friend2在线而friend1不在线，将friend2排在前面
					  if (!isFriend1Online && isFriend2Online) {
						return 1;
					  }
					  // 否则保持原来的顺序
					  return 0;
				});
				let newdata = JSON.parse(JSON.stringify(this.grouplist))
				for (let index in newdata) {
					let data = newdata[index]
					if(data.group_id == 0){
						newdata[index].data = friendData.filter(item=>{
							if(this.searchval && item.friend_remark.indexOf(this.searchval) === -1 && item.nick_name.indexOf(this.searchval) === -1){
								return false
							}
							return item.friend_group == data.group_id || !item.friend_group
						})
					}else{
						newdata[index].data = friendData.filter(item=>{
							if(this.searchval && item.friend_remark.indexOf(this.searchval) === -1 && item.nick_name.indexOf(this.searchval) === -1){
								return false
							}
							return item.friend_group == data.group_id
						})
					}
				}
				console.log(newdata);
				let searchData = newdata.filter(item => {
					// 根据名字筛选
					if (this.searchval && !item.data.length) {
						return false;
					}
					return true;
				});
				console.log(searchData);
				return searchData
			},
			filtrationList(){
				if(this.type == 'card'){
					const filteredData = this.sessionList.filter(item => {
					  // 这里假设你想要根据名字进行过滤
					  return item.chat_type != 'group';
					});
					return filteredData
				}
				return this.sessionList
			},
			messageText() {
				return (text) => {
					return replaceEmojis(text)
				}
			},
			mediaAttachments() {
				return (item) => {
					return item.content_text.filter(a => a.image || a.video);
				}
			},
			searchlist(){
				let newdata = this.indexList.filter(item => {
					// 根据名字筛选
					if (this.searchval && item.group_info && item.group_info.group_name.indexOf(this.searchval) === -1) {
						return false;
					}
					return true;
				});
				return newdata
			}
		},
		onLoad() {
			let query = this.$Route.query
			this.type = query.type
			if(query.chatdata){
				this.chatdata = query.chatdata
			}
			if(query.infodata){
				this.infodata = query.infodata
			}
			this.getlist()
		},
		methods: {
			openFriendGroup(){
				setTimeout(()=>{
					this.$refs.collapse.resize()
				},300)
				// this.$nextTick(()=>{
				// 	this.$refs.collapse.resize()
				// })
			},
			async getlist(){
				try{
					let resapi = await friendGroupApi.list()
					if(resapi){
						this.grouplist = resapi.list
					}
				}catch(e){
					//TODO handle the exception
				}
			},
			async queryList(pageNo, pageSize) {
				try{
					let res = await this.$api.groups.list({page:pageNo,limit:pageSize}) 
					if(res){
						this.$refs.paging.complete(res.data.list)
					}else{
						this.$refs.paging.complete(false)
					}
				}catch(e){
					this.$refs.paging.complete(false)
				}
			},
			itemclick(item){
				if(this.type == 'card'){
					uni.navigateBack({
					  delta: 1,  // 返回的页面数，1 表示返回到上一个页面
					  success() {
					    uni.$emit('onCallingCard', item);
					  }
					});
				}else if(this.type == 'share'){
					this.chatInfo = item
					this.$refs.clShare.show({
						confirmText:this.$t("common.sendConfirm"),
						cancelText:this.$t("common.cancelText"),
						confirm:async (e)=> {
							let content = JSON.parse(JSON.stringify(this.chatdata))
							console.log(this.chatdata);
							const batchSize = 5;  // 每批次发送的最大消息数量
							let batchPromises = [];
							let successCount = 0;
							let failureCount = 0;
							try {
								uni.showLoading({
									title:this.$t("api.loading.msg.send"),
								})
								for (let i = 0; i < this.chatdata.length; i += batchSize) {
									let batch = content.slice(i, i + batchSize).map(async data => {
										let wy_id = uuidv4();
										try {
											await messageApi.directsend({
											  target_id: item.chat_id,
											  local_id: wy_id,
											  msg_type: data.msg_type,
											  content_text: data.content_text
											}, item.chat_type);
											return { success: true };
										} catch (err) {
											return { error: err };
										}
									});
									batchPromises.push(Promise.all(batch));
								}
				
								// 等待所有批次发送完成
								const results = await Promise.all(batchPromises);
								uni.hideLoading()
								e.showModel = false;
								// 统计成功和失败的消息数量
								results.flat().forEach(result => {
									if (result.success) {
									  successCount++;
									} else {
									  failureCount++;
									}
								});
								console.log(successCount);
								
								// 根据统计结果显示弹窗
								if (failureCount > 0) {
									uni.showToast({
									  title: this.$tc("tost.title.sendOkNum",failureCount),
									  icon: 'none'
									});
								} else {
									uni.showToast({
									  title: this.$t("tost.title.sendOk"),
									  icon: 'none'
									});
								}
								setTimeout(()=>{
									uni.navigateBack({
									  delta: 1,  // 返回的页面数，1 表示返回到上一个页面
									});
								}, 1000);
							} catch (e) {
								uni.hideLoading()
								uni.showToast({
									title: e.message || e,
									icon: 'none'
								});
							}
						},
						close:()=> {
							//清空一下放大图片的存储
							this.$store.commit('setImages',[])
						}
					})
				}else if(this.type == 'friend_card'){
					this.chatInfo = item
					console.log(this.chatInfo);
					let wy_id = uuidv4()
					let senddata = {
						target_id: item.chat_id,
						local_id: wy_id,
						msg_type: 'b_c',
						content_text: [
							{
								b_c: {
									card_user_id:this.infodata.user_id,
									nick_name:this.infodata.nick_name,
									avatar_url:this.infodata.avatar_url,
									type:'private',
								}
							}
						]
					}
					this.chatdata = JSON.parse(JSON.stringify(senddata))
					
					this.$refs.clShare.show({
						confirmText:this.$t("common.sendConfirm"),
						cancelText:this.$t("common.cancelText"),
						confirm:async (e)=> {
							try{
								let res = await messageApi.directsend(senddata,item.chat_type)
								uni.showToast({
									title:this.$t("tost.title.sendOk"),
									icon:'none'
								})
								e.showModel = false
								setTimeout(()=>{
									uni.navigateBack({
									  delta: 1,  // 返回的页面数，1 表示返回到上一个页面
									});
								},1000)
							}catch(e){
								uni.showToast({
									title:e,
									icon:'none'
								})
							}
						}
					})
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.shareView{
		width: 100%;
		text-align: left;
		&__title{
			font-size: 28rpx;
			font-weight: bold;
		}
		&__top{
			display: flex;
			align-items: center;
			margin-top: 20rpx;
			&__name{
				margin-left: 10rpx;
				font-size: 26rpx;
			}
		}
		&__content{
			margin-top: 30rpx;
			padding-left: 15rpx;
			&__text{
				font-size: 26rpx;
			}
		}
	}
	.searchview {
		margin: 20rpx 30rpx;
		background-color: #1e1f30;
		border-radius: 60rpx;
		padding-right: 20rpx;
	}

	.listview {
		flex: 1;
		overflow: hidden;
		.listitemtop,
		.listitem {
			display: flex;
			align-items: center;
			padding: 20rpx 30rpx;
			position: relative;
			&.listitem::after {
				content: "";
				position: absolute;
				width: calc(100% - 140rpx);
				background-color: #1E1F30;
				height: 1rpx;
				bottom: 0;
				right: 0;
			}

			&__right {
				margin-left: 20rpx;
				flex: 1;

				&__top {
					display: flex;
					justify-content: space-between;
					align-items: center;

					&__nickname {
						color: #fff;
						font-size: 28rpx;
					}
				}
			}
		}
	}
	.content {
		max-width: 400rpx;
		font-size: 28rpx;
	}
	
	
	.mycollapse{
		display: flex;
		flex-direction: column;
		&__view{
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}
</style>